package com.wechat.server.mp.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.pdd.pop.sdk.common.util.JsonUtil;
import com.pdd.pop.sdk.http.PopClient;
import com.pdd.pop.sdk.http.PopHttpClient;
import com.pdd.pop.sdk.http.api.pop.request.PddOpenDecryptBatchRequest;
import com.pdd.pop.sdk.http.api.pop.request.PddOrderListGetRequest;
import com.pdd.pop.sdk.http.api.pop.request.PddOrderVirtualInformationGetRequest;
import com.pdd.pop.sdk.http.api.pop.request.PddPopAuthTokenCreateRequest;
import com.pdd.pop.sdk.http.api.pop.request.PddPopAuthTokenRefreshRequest;
import com.pdd.pop.sdk.http.api.pop.request.PddTimeGetRequest;
import com.pdd.pop.sdk.http.api.pop.response.PddOpenDecryptBatchResponse;
import com.pdd.pop.sdk.http.api.pop.response.PddOrderListGetResponse;
import com.pdd.pop.sdk.http.api.pop.response.PddOrderVirtualInformationGetResponse;
import com.pdd.pop.sdk.http.api.pop.response.PddPopAuthTokenCreateResponse;
import com.pdd.pop.sdk.http.api.pop.response.PddPopAuthTokenRefreshResponse;
import com.pdd.pop.sdk.http.api.pop.response.PddTimeGetResponse;
import com.wechat.server.mp.config.PddConfig;
import com.wechat.server.mp.dto.OrderExcelModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import com.pdd.pop.sdk.http.api.pop.request.PddOpenDecryptBatchRequest.DataListItem;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @description: service
 * @author: stone
 * @date: Created by 2021/10/9 11:20
 * @version: 1.0.0
 * @pakeage: com.wechat.server.mp.service
 */
@Service
@Slf4j
public class PddService {

    @Autowired
    private PopClient client;


    /**
     * 获取拼多多服务器的系统时间
     *
     * @return
     * @throws Exception
     */
    public  String getTime() throws Exception {
        PddTimeGetRequest request = new PddTimeGetRequest();
        PddTimeGetResponse response = client.syncInvoke(request);
        //System.out.println(JsonUtil.transferToJson(response));
        log.info("pdd放回的数据为 ====> {}", JsonUtil.transferToJson(response));
        PddTimeGetResponse.TimeGetResponse timeGetResponse = response.getTimeGetResponse();

        return timeGetResponse.getTime();
    }


    /**
     * 获取token
     *
     * @param code
     * @return
     * @throws Exception
     */
    public String getAccessToke(String code) throws Exception {
        PddPopAuthTokenCreateRequest request = new PddPopAuthTokenCreateRequest();
        request.setCode(code);
        PddPopAuthTokenCreateResponse response = client.syncInvoke(request);
        PddPopAuthTokenCreateResponse.PopAuthTokenCreateResponse token = response.getPopAuthTokenCreateResponse();
        log.info("pdd 请求的access_token 对象 ====> {}", JsonUtil.transferToJson(response));
        PddConfig.cacheToken.put("token", token.getAccessToken());
        PddConfig.cacheToken.put(token.getAccessToken(), token);
        PddConfig.cacheToken.put("expire", token.getExpiresAt());
        PddConfig.cacheToken.put("refreshToken", token.getRefreshToken());
        return JsonUtil.transferToJson(response);
    }

    /**
     * 定时任务算下token
     *
     * @throws Exception
     */
    //@Scheduled(cron = "0 0 0/1 * * ?")
    public boolean checkToken() throws Exception {
        log.info("执行了没有 ==================> ");
        Long expire = PddConfig.cacheToken.get("expire") == null ? 0L : (Long) PddConfig.cacheToken.get("expire");
        String time = getTime();
        Date date = DateUtil.parse(time, "yyyy-MM-dd hh:mm:ss");
        Long current = date.getTime() / 1000;

        //Long current = Long.parseLong(time)/1000;
        //2*60*60
        if (expire - current <= 2 * 60 * 60) {
            //refresh_token
            return false;
        }
        return true;
    }

    public  void refreshToken() throws Exception {
        PddPopAuthTokenRefreshRequest request = new PddPopAuthTokenRefreshRequest();
        String refreshToken = (String) PddConfig.cacheToken.get("refreshToken");
        request.setRefreshToken(refreshToken);
        PddPopAuthTokenRefreshResponse response = client.syncInvoke(request);
        System.out.println(JsonUtil.transferToJson(response));

        PddPopAuthTokenRefreshResponse.PopAuthTokenRefreshResponse tokenRefreshResponse = response.getPopAuthTokenRefreshResponse();
        PddConfig.cacheToken.put("token", tokenRefreshResponse.getAccessToken());
        PddConfig.cacheToken.put("expire", tokenRefreshResponse.getExpiresAt());
        PddConfig.cacheToken.put("refreshToken", tokenRefreshResponse.getRefreshToken());

    }

    //public static void main(String[] args) throws Exception {
    //    refreshToken();
    //}

    /**
     * 获取订单列表
     * @param num
     * @param page
     * @return
     * @throws Exception
     */
    public  List<OrderExcelModel> getOrderDataList(Integer num, Integer page) throws Exception {
        PddOrderListGetRequest request = new PddOrderListGetRequest();
        request.setOrderStatus(1);
        request.setRefundStatus(1);
        String time = getTime();
        Date date = DateUtil.parse(time, "yyyy-MM-dd hh:mm:ss");
        long current = date.getTime() / 1000;
        long old = 0L;
        if (null == num) {
            old = current - 24 * 3600;
            request.setStartConfirmAt(old);
        }
        //request.setStartConfirmAt(1L);
        request.setEndConfirmAt(current);
        request.setPage(page);
        request.setPageSize(100);
        request.setTradeType(0);
        request.setUseHasNext(false);
        String access_token = (String) PddConfig.cacheToken.get("token");
        PddOrderListGetResponse response = client.syncInvoke(request, access_token);

        log.info("返回的结果是订单列表 ====> {}", JsonUtil.transferToJson(response));
        PddOrderListGetResponse.OrderListGetResponse orderListGetResponse = response.getOrderListGetResponse();
        List<PddOrderListGetResponse.OrderListGetResponseOrderListItem> orderList = orderListGetResponse.getOrderList();
        if (CollUtil.isEmpty(orderList)) {
            return new ArrayList<>();
        }
        Collections.reverse(orderList);

         List<OrderExcelModel> encryptList = orderList.stream().map(e -> {
             String orderSn = e.getOrderSn();
             //获取身份证，名称等信息
             PddOrderVirtualInformationGetResponse.OrderVirtualInformationResponse virtual = this.virtual(orderSn);
             List<PddOrderListGetResponse.OrderListGetResponseOrderListItemItemListItem> itemList = e.getItemList();
             Set<String> skuNames = itemList.stream().map(PddOrderListGetResponse.OrderListGetResponseOrderListItemItemListItem::getGoodsName).collect(Collectors.toSet());
             Set<String> goodSpecs = itemList.stream().map(PddOrderListGetResponse.OrderListGetResponseOrderListItemItemListItem::getGoodsSpec).collect(Collectors.toSet());
             String skuName = StrUtil.join(",", skuNames);
             String goodSpecsStr = StrUtil.join(",", goodSpecs);
             return new OrderExcelModel(orderSn,virtual.getIdCardName() , virtual.getIdCardNum(), e.getReceiverPhone(), e.getAddress(),skuName,goodSpecsStr);
         }).collect(Collectors.toList());

        return decrypt(encryptList);


    }

    //211008-254384619043363

    //姓名  +身份证 +联系电话+地址
    //public static void main(String[] args) throws Exception {
    //    //virtual();
    //    //decrypt();
    //}

    //receiver_name address receiver_phone
    public List<OrderExcelModel> decrypt(List<OrderExcelModel> encryptList) throws Exception {
        if (CollUtil.isEmpty(encryptList)) {
            return null;
        }


        PddOpenDecryptBatchRequest request = new PddOpenDecryptBatchRequest();
        List<DataListItem> dataList = new ArrayList<>();

        encryptList.forEach(e -> {
            List<DataListItem> items = this.toItem(e);
            dataList.addAll(items);
        });

        request.setDataList(dataList);
        String access_token = (String) PddConfig.cacheToken.get("token");
        PddOpenDecryptBatchResponse response = client.syncInvoke(request, access_token);
        PddOpenDecryptBatchResponse.OpenDecryptBatchResponse openDecryptBatchResponse = response.getOpenDecryptBatchResponse();
        log.info("pdd解密的数据为 ====> {}", JsonUtil.transferToJson(response));

        List<PddOpenDecryptBatchResponse.OpenDecryptBatchResponseDataDecryptListItem> dataDecryptList = openDecryptBatchResponse.getDataDecryptList();

        return decryptList(encryptList, dataDecryptList);
        //System.out.println(JsonUtil.transferToJson(response));
    }

    private List<OrderExcelModel> decryptList(List<OrderExcelModel> encryptList, List<PddOpenDecryptBatchResponse.OpenDecryptBatchResponseDataDecryptListItem> dataDecryptList) {
        Map<String, List<PddOpenDecryptBatchResponse.OpenDecryptBatchResponseDataDecryptListItem>> listMap = dataDecryptList.stream().collect(Collectors.groupingBy(PddOpenDecryptBatchResponse.OpenDecryptBatchResponseDataDecryptListItem::getDataTag, Collectors.toList()));

        List<OrderExcelModel> result = new ArrayList<>();
        Map<String, OrderExcelModel> orderExcelModelMap = encryptList.stream().collect(Collectors.toMap(OrderExcelModel::getOrderSn, e -> e));
        listMap.forEach((k, v) -> {
            OrderExcelModel model = orderExcelModelMap.get(k);
            v.forEach(ve -> {
                Integer dataType = ve.getDataType();
                if (dataType.equals(11)) {
                    model.setName(ve.getDecryptedData());
                } else if (dataType.equals(6)) {
                    model.setPhone(ve.getDecryptedData());
                } else if (dataType.equals(7) || dataType.equals(8)) {
                    model.setAddress(ve.getDecryptedData());

                } else if (dataType.equals(10)) {
                    model.setIdCard(ve.getDecryptedData());
                } else {
                    log.info("未知类型 ===> {}", JsonUtil.transferToJson(ve));
                }
            });
            result.add(model);
        });
        return result;
    }

    private List<DataListItem> toItem(OrderExcelModel e) {
        List<DataListItem> items = new ArrayList<>();
        DataListItem item = new DataListItem();
        item.setDataTag(e.getOrderSn());
        item.setEncryptedData(e.getAddress());
        items.add(item);

        DataListItem item2 = new DataListItem();
        item2.setDataTag(e.getOrderSn());
        item2.setEncryptedData(e.getName());
        items.add(item2);
        DataListItem item3 = new DataListItem();
        item3.setDataTag(e.getOrderSn());
        item3.setEncryptedData(e.getPhone());
        items.add(item3);

        DataListItem item4 = new DataListItem();
        item4.setDataTag(e.getOrderSn());
        item4.setEncryptedData(e.getIdCard());
        items.add(item4);
        return items;
    }

    //获取身份证接口
    public PddOrderVirtualInformationGetResponse.OrderVirtualInformationResponse virtual(String orderSn) {

        PddOrderVirtualInformationGetRequest request = new PddOrderVirtualInformationGetRequest();
        request.setOrderSn(orderSn);
        PddOrderVirtualInformationGetResponse response = null;
        try {
            String access_token = (String) PddConfig.cacheToken.get("token");
            response = client.syncInvoke(request, access_token);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //~AgAAAAD/NUYLekvZpAA6TWTRQUtko+5nFB9ff4yQWKQ=~T9pMU5iO~0~~
        //~AgAAAAD/NUYFekvZpAAIJTrScr3Rff0jEH3KvlWu/w8=~rzB/~0~~
        assert response != null;
        log.info("pdd请求身份证接口返回的数据为 ====> {}", JsonUtil.transferToJson(response));
        return response.getOrderVirtualInformationResponse();
    }


}
